package com.atguigu.gulimall_product.product.controller;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;


import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.atguigu.gulimall_product.product.entity.BrandEntity;
import com.atguigu.gulimall_product.product.service.BrandService;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.R;
import org.springframework.web.multipart.MultipartFile;


/**
 * 品牌
 *
 * @author chenzhengping
 * @email 1840854390@gmail.com
 * @date 2023-10-27 16:43:16
 */
@RestController
@RequestMapping("product/brand")
public class BrandController {
    @Autowired
    private BrandService brandService;
    @RequestMapping("/InsertTest")
    public String testInsert(){
        BrandEntity brandEntity=new BrandEntity();
        brandEntity.setName("华为");
        boolean save = brandService.save(brandEntity);
        String s1;
        if(save){
        s1="连接数据库成功并且插入一条数据";
        }else{
        s1="添加数据失败";
        }
        return s1;
    }

    /**
     * 列表
     */

    @RequestMapping("/list")
   // @RequiresPermissions("product:brand:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = brandService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{brandId}")
    //@RequiresPermissions("product:brand:info")
    public R info(@PathVariable("brandId") Long brandId){
		BrandEntity brand = brandService.getById(brandId);

        return R.ok().put("brand", brand);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    //@RequiresPermissions("product:brand:save")
    public R save(@RequestBody BrandEntity brand){
		brandService.save(brand);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    //@RequiresPermissions("product:brand:update")
    public R update(@RequestBody BrandEntity brand){
		brandService.updateById(brand);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    //@RequiresPermissions("product:brand:delete")
    public R delete(@RequestBody Long[] brandIds){
		brandService.removeByIds(Arrays.asList(brandIds));

        return R.ok();
    }
    @RequestMapping(value = "UpFile",method = RequestMethod.POST)
    public R UpFile(@RequestParam(name="file_up") MultipartFile multipartfile) throws com.aliyuncs.exceptions.ClientException {

        /**
         * String fileName = multiFile.getOriginalFilename();
         *     // 获取文件后缀(.xml)
         *     String suffix = fileName.substring(fileName.lastIndexOf("."));
         *     // 若要防止生成的临时文件重复,需要在文件名后添加随机码
         *     try {
         *         //"tmp", ".txt"
         *         //fileName这块可以根据自己的业务需求进行修改，我这里没有做任何处理
         *         File file = File.createTempFile(fileName, suffix);
         *         multiFile.transferTo(file);
         *         return file;
         *     } catch (Exception e) {
         *         logger.error("MultipartFile转File失败",e);
         *     }
         *     return null;
         *LTAI5tDn4zxUdLzKFk5wAU42
         * YrwzUEpxmFqMxy6GSpsYBqxlHaeeqj
         */
// RAM用户的访问密钥（AccessKey ID和AccessKey Secret）。
        String accessKeyId = "LTAI5tDn4zxUdLzKFk5wAU42";
        String accessKeySecret = "YrwzUEpxmFqMxy6GSpsYBqxlHaeeqj";
// 使用代码嵌入的RAM用户的访问密钥配置访问凭证。
        CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "guli-czp";
        String fileName = multipartfile.getOriginalFilename();
        int dotIndex = fileName.lastIndexOf('.');
        String substring = fileName.substring(dotIndex + 1);
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String format=new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String objectName = format+"/"+fileName;
        // 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。
        // 如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
        String url="https://guli-czp.oss-cn-hangzhou.aliyuncs.com/"+objectName;
        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, multipartfile.getInputStream());
            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);

        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        R ok = R.ok();
        ok.put("url",url);
        return ok;
    }
}
